<template>
  <div class="cart">
    <el-card class="cart-card">
      <div slot="header" class="cart-header">
        <span>我的购物车</span>
        <el-button
          type="text"
          :disabled="!cartItems.length"
          @click="handleClearCart">
          清空购物车
        </el-button>
      </div>

      <!-- 购物车为空 -->
      <el-empty
        v-if="!cartItems.length"
        description="购物车还是空的"
        :image-size="200">
        <el-button type="primary" @click="$router.push('/main/shop')">
          去购物
        </el-button>
      </el-empty>

      <!-- 购物车列表 -->
      <div v-else class="cart-list">
        <div
          v-for="item in cartItems"
          :key="item.id"
          class="cart-item">
          <div class="item-select">
            <el-checkbox
              v-model="item.selected"
              @change="(val) => handleItemSelect(item.id, val)">
            </el-checkbox>
          </div>
          <div class="item-image">
            <img :src="getImageUrl(item.productImage)" :alt="item.productName">
          </div>
          <div class="item-info">
            <h3 class="item-name">{{ item.productName }}</h3>
            <div class="item-price">
              <span class="price">¥{{ item.price }}</span>
            </div>
          </div>
          <div class="item-quantity">
            <el-input-number
              v-model="item.quantity"
              :min="1"
              size="small"
              @change="(val) => handleQuantityChange(item.id, val)">
            </el-input-number>
          </div>
          <div class="item-total">
            <span class="total-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
          </div>
          <div class="item-actions">
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="small"
              @click="handleRemoveItem(item.id)">
            </el-button>
          </div>
        </div>

        <!-- 购物车底部 -->
        <div class="cart-footer">
          <div class="select-all">
            <el-checkbox v-model="selectAll" @change="handleSelectAllChange">全选</el-checkbox>
          </div>
          <div class="total-info">
            <span>已选择 {{ selectedCount }} 件商品</span>
            <span class="total-price">合计：¥{{ totalPrice }}</span>
          </div>
          <el-button type="primary" :disabled="selectedCount === 0" @click="handleCheckout">
            去结算
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  name: 'Cart',
  data() {
    return {
      selectedItems: new Set(),
      isUpdatingSelection: false
    }
  },
  computed: {
    ...mapState('cart', ['cartItems']),
    selectedCount() {
      return this.cartItems.filter(item => item.selected).length
    },
    selectAll: {
      get() {
        return this.cartItems.length > 0 && this.cartItems.every(item => item.selected)
      },
      set(value) {
        this.isUpdatingSelection = true
        this.cartItems.forEach(item => {
          item.selected = value
        })
        
        if (value) {
          this.selectedItems = new Set(this.cartItems.map(item => item.id))
        } else {
          this.selectedItems.clear()
        }
        this.isUpdatingSelection = false
      }
    },
    totalPrice() {
      return this.cartItems
        .filter(item => item.selected)
        .reduce((total, item) => total + (item.price * item.quantity), 0)
        .toFixed(2)
    }
  },
  watch: {
    cartItems: {
      handler() {
        if (!this.isUpdatingSelection) {
          this.syncSelectedItems()
        }
      },
      deep: true
    }
  },
  created() {
    this.fetchCartItems()
  },
  methods: {
    ...mapActions('cart', [
      'getCartItems',
      'updateCartItemQuantity',
      'removeFromCart',
      'clearCart'
    ]),
    syncSelectedItems() {
      this.selectedItems = new Set(
        this.cartItems
          .filter(item => item.selected)
          .map(item => item.id)
      )
    },
    async fetchCartItems() {
      try {
        await this.getCartItems()
        this.cartItems.forEach(item => {
          this.$set(item, 'selected', false)
        })
        this.selectedItems.clear()
      } catch (error) {
        this.$message.error('获取购物车失败')
      }
    },
    async handleQuantityChange(id, quantity) {
      try {
        await this.updateCartItemQuantity({ id, quantity })
      } catch (error) {
        this.$message.error('更新数量失败')
      }
    },
    handleItemSelect(itemId, selected) {
      if (selected) {
        this.selectedItems.add(itemId)
      } else {
        this.selectedItems.delete(itemId)
      }
      
      this.$forceUpdate()
    },
    async handleRemoveItem(id) {
      try {
        await this.$confirm('确定要从购物车中移除该商品吗？', '提示', {
          type: 'warning'
        })
        await this.removeFromCart(id)
        this.selectedItems.delete(id)
        this.$message.success('已移除商品')
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('移除商品失败')
        }
      }
    },
    async handleClearCart() {
      try {
        await this.$confirm('确定要清空购物车吗？', '提示', {
          type: 'warning'
        })
        await this.clearCart()
        this.selectedItems.clear()
        this.$message.success('已清空购物车')
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('清空购物车失败')
        }
      }
    },
    handleSelectAllChange(value) {
      this.selectAll = value
    },
    handleCheckout() {
      const selectedItems = this.cartItems.filter(item => item.selected)
      if (selectedItems.length === 0) {
        this.$message.warning('请选择要结算的商品')
        return
      }
      
      this.$store.commit('checkout/SET_CHECKOUT_ITEMS', selectedItems)
      this.$router.push('/main/shop/checkout')
    },
    getImageUrl(path) {
      if (!path) {
        return require('@/assets/default.jpg');
      }
      
      // 服务器地址
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果路径已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      
      // 确保路径以 / 开头
      if (!path.startsWith('/')) {
        path = '/' + path;
      }
      
      // 构建完整URL
      return serverUrl + path;
    }
  }
}
</script>

<style lang="scss" scoped>
.cart {
  padding: 20px;

  .cart-card {
    .cart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .cart-list {
      .cart-item {
        display: flex;
        align-items: center;
        padding: 20px 0;
        border-bottom: 1px solid #eee;

        &:last-child {
          border-bottom: none;
        }

        .item-select {
          margin-right: 20px;
          min-width: 40px; /* 增加点击区域 */
          display: flex;
          align-items: center;
          justify-content: center;
          
          .el-checkbox {
            cursor: pointer;
            
            /* 增加复选框的点击区域 */
            ::v-deep .el-checkbox__input {
              cursor: pointer;
              padding: 5px;
            }
            
            /* 增强复选框标签的可见性 */
            ::v-deep .el-checkbox__label {
              padding-left: 8px;
            }
          }
        }

        .item-image {
          width: 100px;
          height: 100px;
          margin-right: 20px;
          overflow: hidden;
          border-radius: 4px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .item-info {
          flex: 1;
          margin-right: 20px;

          .item-name {
            margin: 0 0 10px;
            font-size: 16px;
          }

          .item-price {
            color: #666;

            .price {
              color: #f56c6c;
              font-weight: bold;
            }
          }
        }

        .item-quantity {
          margin-right: 20px;
          
          .el-input-number {
            width: 120px;
          }
        }

        .item-total {
          margin-right: 20px;
          min-width: 80px;
          text-align: right;

          .total-price {
            color: #f56c6c;
            font-size: 16px;
            font-weight: bold;
          }
        }

        .item-actions {
          min-width: 50px;
          text-align: center;
        }
      }

      .cart-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 20px;
        padding: 20px 0;
        border-top: 1px solid #eee;

        .select-all {
          margin-right: 20px;
        }

        .total-info {
          flex: 1;
          text-align: right;
          margin-right: 20px;

          .total-price {
            margin-left: 20px;
            color: #f56c6c;
            font-size: 18px;
            font-weight: bold;
          }
        }
      }
    }
  }
}
</style> 